const mongoose = require('mongoose')
const { resolve } = require('path')
const glob = require('glob')
const db = 'mongodb://localhost/douban-test'
mongoose.Promise = global.Promise

exports.initSchema = () => {
  return new Promise((res) => {
    glob.sync(resolve(__dirname, './schema', '**/*.js')).forEach(require);
    res()
  })
}

exports.initAdmin = async () => {
  const User = mongoose.model('User')
  let user = await User.findOne({
    username: 'admin'
  })
  // username: 'fanchao',
  //   email: '1178806579@qq.com',
  //   password: 'fanchao',
  //   role: 'admin'
  if (!user) {
    const user = new User({
      username: 'admin',// admin1 同
      email: 'test1@qq.com',
      password: 'superAdmin',
      role: 'superAdmin'
    })
    await user.save()
  }
}
exports.connect = () => {
  let maxConnectTimes = 0
  return new Promise((res, rej) => {
    if (process.env.NODE_ENV !== 'production') {
      mongoose.set('debug', true)
    }

    mongoose.connect(db, { useNewUrlParser: true })

    mongoose.connection.on('disconnected', () => {
      maxConnectTimes++
      if (maxConnectTimes < 3) {
        mongoose.connect(db)
      } else {
        throw new Error('数据库挂了')
      }
    })

    mongoose.connection.on('error', (err) => {
      rej(err)
      console.log('err', err)
    })

    mongoose.connection.once('open', () => {
      // const Dog = mongoose.model('Dog', { name: String })
      // const doga = new Dog({name: 'little dog'})
      // doga.save().then(() => {
      //   console.log('保存成功！')
      // })
      res()
      console.log('mongoDB connected successfully!')
    })
  })
}